"""
课程管理API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.course import Course, CourseStage
from app.schemas.course import (
    CourseCreate, CourseUpdate, CourseResponse,
    CourseStageCreate, CourseStageResponse
)
from app.api.deps import get_current_active_user

router = APIRouter()


@router.get("/")
def get_courses(
    db: Session = Depends(get_db),
    page: int = 1,
    size: int = 100,
    name: str = None,
    subject_id: int = None,
    # current_user: Any = Depends(get_current_active_user)  # 临时移除认证要求
) -> Any:
    """
    获取课程列表
    """
    query = db.query(Course)
    
    # 添加搜索条件
    if name:
        query = query.filter(Course.name.contains(name))
    if subject_id:
        query = query.filter(Course.subject_id == subject_id)
    
    # 计算总数
    total = query.count()
    
    # 分页
    skip = (page - 1) * size
    courses = query.offset(skip).limit(size).all()
    
    # 将SQLAlchemy模型转换为字典
    courses_data = []
    for course in courses:
        course_dict = {
            "id": course.id,
            "name": course.name,
            "description": course.description,
            "total_stages": course.total_stages,
            "total_price": float(course.total_price) if course.total_price else 0.0,
            "subject_id": course.subject_id,
            "status": course.status,
            "created_at": course.created_at.isoformat() if course.created_at else None,
            "updated_at": course.updated_at.isoformat() if course.updated_at else None
        }
        courses_data.append(course_dict)
    
    return {
        "items": courses_data,
        "total": total,
        "page": page,
        "size": size
    }


@router.get("/{course_id}", response_model=CourseResponse)
def get_course(
    course_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    获取单个课程信息
    """
    course = db.query(Course).filter(Course.id == course_id).first()
    if not course:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="课程不存在"
        )
    return course


@router.post("/", response_model=CourseResponse)
def create_course(
    *,
    db: Session = Depends(get_db),
    course_in: CourseCreate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    创建新课程
    """
    course = Course(**course_in.dict())
    db.add(course)
    db.commit()
    db.refresh(course)
    return course


@router.put("/{course_id}", response_model=CourseResponse)
def update_course(
    *,
    db: Session = Depends(get_db),
    course_id: int,
    course_in: CourseUpdate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    更新课程信息
    """
    course = db.query(Course).filter(Course.id == course_id).first()
    if not course:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="课程不存在"
        )
    
    update_data = course_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(course, field, value)
    
    db.add(course)
    db.commit()
    db.refresh(course)
    return course


@router.delete("/{course_id}")
def delete_course(
    *,
    db: Session = Depends(get_db),
    course_id: int,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    删除课程
    """
    course = db.query(Course).filter(Course.id == course_id).first()
    if not course:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="课程不存在"
        )
    
    db.delete(course)
    db.commit()
    return {"message": "课程删除成功"}


# 课程阶段相关API
@router.get("/{course_id}/stages", response_model=List[CourseStageResponse])
def get_course_stages(
    course_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    获取课程阶段列表
    """
    stages = db.query(CourseStage).filter(CourseStage.course_id == course_id).all()
    return stages


@router.post("/{course_id}/stages", response_model=CourseStageResponse)
def create_course_stage(
    *,
    course_id: int,
    db: Session = Depends(get_db),
    stage_in: CourseStageCreate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    创建课程阶段
    """
    # 检查阶段序号是否重复
    existing_stage = db.query(CourseStage).filter(
        CourseStage.course_id == course_id,
        CourseStage.stage_number == stage_in.stage_number
    ).first()
    if existing_stage:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="阶段序号已存在"
        )
    
    stage_data = stage_in.dict()
    stage_data["course_id"] = course_id
    stage = CourseStage(**stage_data)
    db.add(stage)
    db.commit()
    db.refresh(stage)
    return stage
